package com.mxx.qh.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;

import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.security.identity.IdentityCredentialException;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.mxx.qh.SPUtils;
import com.mxx.qh.WXAuthorizeBroadCast;
import com.mxx.qh.WXPayResultBroadCast;
import com.mxx.qh.WXPayResultListener;
import com.mxx.qh.WxAuthorizeInfoListener;
import com.mxx.qh.config.NetUrlConfig;
import com.mxx.qh.dialog.AppExitDialog;
import com.mxx.qh.dialog.AppUpdateDialog;
import com.mxx.qh.dialog.IdentificationUnknownDialog;
import com.mxx.qh.dialog.PlaybillDialog;
import com.mxx.qh.dialog.ResultDialog;
import com.mxx.qh.dialog.TokenEmptyDialog;
import com.mxx.qh.interfaces.IException;
import com.mxx.qh.interfaces.ILoading;
import com.mxx.qh.R;
import com.mxx.qh.config.ConstantsConfig;
import com.mxx.qh.network.DownloadObserver;
import com.mxx.qh.network.RequestEnum;
import com.mxx.qh.network.RetrofitHelper;
import com.mxx.qh.network.StringObserver;
import com.mxx.qh.request.RequestQQ;
import com.mxx.qh.response.AuthorizeInfo;
import com.mxx.qh.response.BannerResponse;
import com.mxx.qh.response.BaseResponse;
import com.mxx.qh.request.RequestBigRecharge;
import com.mxx.qh.request.RequestSmallAdTaskAdd;
import com.mxx.qh.request.RequestTaskPay;
import com.mxx.qh.response.PayResult;
import com.mxx.qh.request.RequestPublicTask;
import com.mxx.qh.response.SaveImageResponse;
import com.mxx.qh.response.ShareContent;
import com.mxx.qh.request.RequestBuyVip;
import com.mxx.qh.response.UpdateResponse;
import com.mxx.qh.response.WXOrderInfo;
import com.mxx.qh.response.WXUserInfo;
import com.mxx.qh.response.ZFBOrderInfo;
import com.mxx.qh.utils.PackageUtils;
import com.mxx.qh.utils.QQShareUtils;
import com.mxx.qh.utils.WebViewUtils;
import com.mxx.qh.utils.WxShareUtils;
import com.mxx.qh.widget.LollipopFixedWebView;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yp.loading.widget.LoadingDialog;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;

public class MainActivity extends BaseActivity implements WXPayResultListener
        , TokenEmptyDialog.WxAuthorizeListener, WxAuthorizeInfoListener
        , IdentificationUnknownDialog.OpenWxListener {
    private LollipopFixedWebView webView;
    private LoadingDialog loadingDialog;
    private ILoading iLoading;
    private IException iException;
    private ShareContent shareContent;
    private RequestTaskPay requestTaskPay;
    private RequestBigRecharge requestBigRecharge;
    private RequestSmallAdTaskAdd requestSmallAdTaskAdd;
    private RequestBuyVip requestBuyVip;
    private RequestPublicTask requestPublicTask;
    private WXPayResultBroadCast wxPayResultBroadCast;
    private WXAuthorizeBroadCast wxAuthorizeBroadCast;
    private RelativeLayout fl_video;
    private ImageView iv_background;
    private WebChromeClient.CustomViewCallback mCustomViewCallback;
    //  横屏时，显示视频的view
    private View mCustomView;
    private final Map<Object, Object> paramsMap = new HashMap<>();
    private final String ORDER_ID = "order_id";
    private final String DOWNLOAD_URL = "download_url";
    private final int ACTION_SHARE_TO_WX = 1;
    private final int ACTION_SHARE_TO_WX_ZONE = 2;
    private final int ACTION_SHARE_TO_QQ = 3;
    private final int ACTION_SHARE_TO_QQ_ZONE = 4;

    /**
     * share/task/payment
     * handleTask()
     */
    private final int ACTION_APP_TASK_PAY = 5;
    /**
     * share/bigrecharge/payment
     * handleBig()
     */

    private final int ACTION_APP_BIG_AD_RECHARGE = 6;
    /**
     * share/extendtask/payment
     * handleSmall()
     */

    private final int ACTION_APP_SMALL_AD_TASK_ADD = 7;
    /**
     * share/extendtask/payment
     * handle();
     */

    private final int ACTION_APP_BUY_VIP = 8;
    /**
     * task/app/issue/task
     * publicTask()
     */
    private final int ACTION_APP_ISSUE_TASK = 9;
    private int action;
    private final Handler mHandler = new Handler();
    private final Runnable mUpdateRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.removeCallbacks(mUpdateRunnable);
            String url = (String) paramsMap.get(DOWNLOAD_URL);
            openBrowser(MainActivity.this, url);
        }
    };
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.removeCallbacks(mRunnable);
            int type;
            switch (action) {
                case ACTION_SHARE_TO_WX:
                case ACTION_SHARE_TO_WX_ZONE:
                case ACTION_SHARE_TO_QQ:
                case ACTION_SHARE_TO_QQ_ZONE:
                    type = getType(shareContent);
                    shareByType(type);
                    break;
                case ACTION_APP_TASK_PAY:
                    runOnUiThread(() -> webView.reload());
                    type = getType(requestTaskPay);
                    sendRequest(action, type);
                    break;
                case ACTION_APP_BIG_AD_RECHARGE:
                    runOnUiThread(() -> webView.reload());
                    type = getType(requestBigRecharge);
                    sendRequest(action, type);
                    break;
                case ACTION_APP_SMALL_AD_TASK_ADD:
                    runOnUiThread(() -> webView.reload());
                    type = getType(requestSmallAdTaskAdd);
                    sendRequest(action, type);
                    break;
                case ACTION_APP_BUY_VIP:
                    runOnUiThread(() -> webView.reload());
                    type = getType(requestBuyVip);
                    sendRequest(action, type);
                    break;
                case ACTION_APP_ISSUE_TASK:
                    runOnUiThread(() -> webView.reload());
                    type = getType(requestPublicTask);
                    sendRequest(action, type);
                    break;
            }
        }
    };

    private int getType(Object object) {
        if (object instanceof ShareContent) {
            return shareContent.type;
        }
        if (object instanceof RequestTaskPay) {
            return Integer.parseInt(requestTaskPay.pay_method);
        }
        if (object instanceof RequestBigRecharge) {
            return Integer.parseInt(requestBigRecharge.pay_method);
        }
        if (object instanceof RequestSmallAdTaskAdd) {
            return Integer.parseInt(requestSmallAdTaskAdd.pay_method);
        }
        if (object instanceof RequestBuyVip) {
            return Integer.parseInt(requestBuyVip.pay_method);
        }
        if (object instanceof RequestPublicTask) {
            return Integer.parseInt(requestPublicTask.pay_method);
        }
        return 1;
    }

    private void shareByType(int type) {
        iLoading.onStart();
        if (type == 1)//分享微信好友
        {
            wxShare(type, iLoading, iException);
        }
        if (type == 2)//分享微信朋友圈
        {
            wxShare(type, iLoading, iException);
        }
        if (type == 3)//分享QQ好友
        {
            qqShare(type, iLoading, iException);
        }
        if (type == 4)//分享QQ空间
        {
            qqShare(type, iLoading, iException);
        }

    }

    private void wxShare(int type, ILoading iLoading, IException iException) {
        Glide
                .with(MainActivity.this)
                .asBitmap()
                .load(shareContent.imgUrl)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        WxShareUtils.share(MainActivity.this, ConstantsConfig.WX_APP_ID
                                , type, shareContent.link, shareContent.title, shareContent.desc, resource
                                , iLoading, iException);
                    }
                });
    }

    private void qqShare(int type, ILoading iLoading, IException iException) {
        QQShareUtils.share(this, ConstantsConfig.QQ_APP_ID
                , type, shareContent.title, shareContent.desc, shareContent.link, shareContent.imgUrl
                , iLoading, iException);
    }

    private String getRequestUrl(int action) {
        String url = "";
        switch (action) {
            case ACTION_APP_TASK_PAY:
                url = "share/task/payment";
                break;
            case ACTION_APP_BIG_AD_RECHARGE:
                url = "share/bigrecharge/payment";
                break;
            case ACTION_APP_SMALL_AD_TASK_ADD:
                url = "share/extendtask/payment";
                break;
            case ACTION_APP_BUY_VIP:
                url = "share/buyMeber/payment";
                break;
            case ACTION_APP_ISSUE_TASK:
                url = "task/app/issue/task";
                break;
        }
        return url;
    }

    private Object getRequestParams(int action) {
        Object object = null;
        switch (action) {
            case ACTION_APP_TASK_PAY:
                object = requestTaskPay;
                break;
            case ACTION_APP_BIG_AD_RECHARGE:
                object = requestBigRecharge;
                break;
            case ACTION_APP_SMALL_AD_TASK_ADD:
                object = requestSmallAdTaskAdd;
                break;
            case ACTION_APP_BUY_VIP:
                object = requestBuyVip;
                break;
            case ACTION_APP_ISSUE_TASK:
                object = requestPublicTask;
                break;
        }
        return object;
    }

    private void sendRequest(int action, int type) {
        String requestUrl = getRequestUrl(action);
        Object requestParams = getRequestParams(action);
        if (requestUrl == null || requestUrl.isEmpty() || requestParams == null) {
            iException.handlerException("请求参数为空");
            return;
        }
        iLoading.onStart();
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL_1)
                .appendUrl(requestUrl)
                .addParams(requestParams)
                .build()
                .observable(RequestEnum.METHOD_POST_WITH_PARAMS)
                .subscribe(new StringObserver() {
                    @Override
                    protected void onSuccess(String json) {
                        handlerSuccessJson(json, type);
                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        handlerFailed(code, msg);
                    }
                });
    }

    private void handlerSuccessJson(String json, int type) {
        iLoading.onFinish();
        try {
            BaseResponse<Object> response = getBaseResponse(json);
            int code = getCode(response);
            if (code == 0) {
                if (type == 1)//支付宝支付
                {
                    ZFBOrderInfo info = getZFBOrderInfo(json);
                    zfbPay(info);

                }
                if (type == 2)//微信支付
                {
                    registerPayBroadCast();
                    WXOrderInfo info = getWXOrderInfo(json);
                    wxPay(info);
                }
            } else {
                String message = getMessage(response);
                iException.handlerException(message);
            }
        } catch (Exception e) {
            iException.handlerException(e.getMessage());
        }
    }

    private BaseResponse<Object> getBaseResponse(String json) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        return new Gson().newBuilder().create()
                .fromJson(json, new TypeToken<BaseResponse<Object>>() {
                }.getType());
    }

    private int getCode(BaseResponse<Object> response) {
        if (response == null) {
            return -1;
        }
        return response.code;
    }

    private String getMessage(BaseResponse<Object> response) {
        if (response == null) {
            return "数据为空";
        }
        return response.message;
    }

    private ZFBOrderInfo getZFBOrderInfo(String json) {
        Gson gson = new Gson();
        if (json != null && !json.isEmpty()) {
            BaseResponse<ZFBOrderInfo> response = gson.fromJson(json, new TypeToken<BaseResponse<ZFBOrderInfo>>() {
            }.getType());
            if (response != null && response.data != null) {
                return gson.fromJson(gson.toJson(response.data), new TypeToken<ZFBOrderInfo>() {
                }.getType());
            }
        }


        return null;
    }

    private void zfbPay(ZFBOrderInfo orderInfo) {
        if (orderInfo == null || orderInfo.pay_info == null || orderInfo.pay_info.isEmpty()) {
            iException.handlerException("支付宝订单信息为空");
            return;
        }
        paramsMap.put(ORDER_ID, orderInfo.order_id);
        new Thread(() -> {
            PayTask payTask = new PayTask(this);
            Map<String, String> result = payTask.payV2(orderInfo.pay_info, true);
            PayResult payResult = new PayResult(result);
            /*
             *对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultStatus = payResult.getResultStatus();


            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "支付成功", Toast.LENGTH_SHORT).show());

            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "支付失败", Toast.LENGTH_SHORT).show());
            }
            runOnUiThread(() -> {
                String orderId = (String) paramsMap.get(ORDER_ID);
                if (orderId != null) {
                    webView.loadUrl("javascript:paySuccess(\"" + orderId + "\")");
                }
            });

        }).start();
    }

    private void registerPayBroadCast() {
        wxPayResultBroadCast = new WXPayResultBroadCast();
        wxPayResultBroadCast.setWxPayResultListener(this);
        registerReceiver(wxPayResultBroadCast, new IntentFilter(WXPayResultBroadCast.WX_AUTHORIZE_ACTION));
    }

    private WXOrderInfo getWXOrderInfo(String json) {
        Gson gson = new Gson();
        if (json != null && !json.isEmpty()) {
            BaseResponse<WXOrderInfo> response = gson.fromJson(json, new TypeToken<BaseResponse<WXOrderInfo>>() {
            }.getType());
            if (response != null && response.data != null) {
                return gson.fromJson(gson.toJson(response.data), new TypeToken<WXOrderInfo>() {
                }.getType());
            }
        }
        return null;
    }

    private void wxPay(WXOrderInfo response) {
        if (response == null) {
            iException.handlerException("微信订单信息为空");
            return;
        }
        paramsMap.put(ORDER_ID, response.order_id);
        IWXAPI api = WXAPIFactory.createWXAPI(this, ConstantsConfig.WX_APP_ID, false);
        if (!api.isWXAppInstalled()) {
            iException.handlerException("您尚未安装微信");
            return;
        }
        WXOrderInfo.PayInfoDTO payInfoDTO = response.pay_info;
        if (payInfoDTO == null) {
            iException.handlerException("微信订单信息为空");
            return;
        }
        api.isWXAppInstalled();
        PayReq request = new PayReq();
        request.appId = ConstantsConfig.WX_APP_ID;
        request.partnerId = payInfoDTO.partnerid;
        request.prepayId = payInfoDTO.prepayid;
        request.nonceStr = payInfoDTO.noncestr;
        request.timeStamp = payInfoDTO.timestamp;
        request.packageValue = payInfoDTO.packagex;
        request.sign = payInfoDTO.sign;
        api.sendReq(request);
    }

    private void handlerFailed(Integer code, String msg) {
        iLoading.onFinish();
        String message = "";
        if (code != null) {
            message = message + code + "\n";
        }
        message = message + msg;
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void setStatusBar() {
        ImmersionBar
                .with(this)
                .fitsSystemWindows(true)
                .statusBarColor(android.R.color.transparent)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    protected void initView() {
        fl_video = findViewById(R.id.fl_video);
        iv_background = findViewById(R.id.iv_background);

        fl_video.getBackground().mutate().setAlpha(255);
        initWebView();
    }

    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    private void initWebView() {
        webView = findViewById(R.id.web_view);
        WebViewUtils.initWebView(this, webView, new WebViewUtils.UrlHandlerListener() {
            @Override
            public void handlerUrl(String url) {
                Log.i("TAG", url);
            }

            @Override
            public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
                //如果view 已经存在，则隐藏
                if (mCustomView != null) {
                    callback.onCustomViewHidden();
                    return;
                }
                view.setBackgroundColor(getResources().getColor(R.color.white));
                mCustomView = view;
                mCustomView.setVisibility(View.VISIBLE);
                mCustomViewCallback = callback;
                fl_video.addView(mCustomView);
                fl_video.setVisibility(View.VISIBLE);
                fl_video.bringToFront();

                //设置横屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);


            }

            @Override
            public void onHideCustomView() {
                if (mCustomView == null) {
                    return;
                }
                mCustomView.setVisibility(View.GONE);
                fl_video.removeView(mCustomView);
                mCustomView = null;
                fl_video.setVisibility(View.GONE);
                try {
                    mCustomViewCallback.onCustomViewHidden();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
            }
        });
        webView.addJavascriptInterface(new ThirdPlatformShare(), "share");
        webView.addJavascriptInterface(new ThirdPlatformPay(), "payment");
        webView.addJavascriptInterface(new ThirdPlatformWx(), "openWeixin");
        webView.addJavascriptInterface(new SaveImage(), "saveImg");
        webView.addJavascriptInterface(new AppUpdate(), "appClick");
        webView.addJavascriptInterface(new BannerPlay(), "videoPlay");
    }

    /**
     * 横竖屏切换监听
     */
    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_SQUARE:
                break;
            case Configuration.ORIENTATION_UNDEFINED:
                break;
        }
    }

    @Override
    protected void initData() {
        String token = (String) SPUtils.get(this, ConstantsConfig.TOKEN, "1");
        if (token != null && !token.isEmpty() && !token.equals("1")) {
            String str_is_sex = (String) SPUtils.get(MainActivity.this, ConstantsConfig.IS_SEX, "");
            if (str_is_sex != null && !str_is_sex.isEmpty()) {
                int is_sex = Integer.parseInt(str_is_sex);
                if (is_sex == 0 || is_sex == 1 || is_sex == 2) {
                    if (is_sex == 2) {
                        showFriendlyHintDialog();
                    }
                    if (is_sex == 0 || is_sex == 1) {
                        String url = NetUrlConfig.BASE_URL + "/#/authorize1/" + token + "&app=app";
                        webView.loadUrl(url);
                        int currentCode = PackageUtils.getVersionCode(MainActivity.this);
                        checkVersion(currentCode, false);
                    }
                }else {
                    showFriendlyHintDialog();
                }
            }else {
                showFriendlyHintDialog();
            }
        } else {
            runOnUiThread(() -> {
                iv_background.setVisibility(View.VISIBLE);
                showAuthorizeLoginDialog();
            });

        }
    }

    private void showLoading() {
        loadingDialog = new LoadingDialog();
        loadingDialog.show(getSupportFragmentManager(), "LoadingDialog");
    }


    private void hideLoading() {
        runOnUiThread(() -> {
            if (loadingDialog == null) {
                return;
            }
            loadingDialog.dismiss();
        });

    }


    @Override
    protected void initListener() {
        super.initListener();
        iLoading = new ILoading() {
            @Override
            public void onStart() {
                runOnUiThread(() -> showLoading());
            }

            @Override
            public void onFinish() {
                runOnUiThread(() -> hideLoading());
            }
        };
        iException = err -> runOnUiThread(() -> Toast.makeText(MainActivity.this, err, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void wxPaySuccess(int code) {
        unregisterReceiver(wxPayResultBroadCast);
        runOnUiThread(() -> {
            Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
            String orderId = (String) paramsMap.get(ORDER_ID);
            if (orderId != null) {
                webView.loadUrl("javascript:paySuccess(\"" + orderId + "\")");
            }
        });

    }

    @Override
    public void wxPayFail(String err) {
        unregisterReceiver(wxPayResultBroadCast);
        runOnUiThread(() -> {
            Toast.makeText(MainActivity.this, err, Toast.LENGTH_SHORT).show();
            String orderId = (String) paramsMap.get(ORDER_ID);
            if (orderId != null) {
                webView.loadUrl("javascript:paySuccess(\"" + orderId + "\")");
            }
        });
    }


    class ThirdPlatformShare {
        @android.webkit.JavascriptInterface
        public void handle(String s) {
            shareContent = getShareContent(s);
            action = getShareAction(shareContent);
            mHandler.postDelayed(mRunnable, 0);
        }
    }

    private ShareContent getShareContent(String s) {
        Gson gson = new Gson();
        ShareContent content = null;
        try {
            content = gson.fromJson(s, new TypeToken<ShareContent>() {
            }.getType());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return content;
    }

    private int getShareAction(ShareContent shareContent) {
        if (shareContent == null) {
            return ACTION_SHARE_TO_WX;
        }
        if (shareContent.type == ACTION_SHARE_TO_WX) {
            return ACTION_SHARE_TO_WX;
        }
        if (shareContent.type == ACTION_SHARE_TO_WX_ZONE) {
            return ACTION_SHARE_TO_WX_ZONE;
        }
        if (shareContent.type == ACTION_SHARE_TO_QQ) {
            return ACTION_SHARE_TO_QQ;
        }
        if (shareContent.type == ACTION_SHARE_TO_QQ_ZONE) {
            return ACTION_SHARE_TO_QQ_ZONE;
        }
        return ACTION_SHARE_TO_WX;
    }

    class ThirdPlatformPay {
        @android.webkit.JavascriptInterface
        /*
         *描述：APP任务支付
         *请求Url:share/task/payment
         */
        public void handleTask(String s) {
            Log.i("TAG", "");
//            Toast.makeText(MainActivity.this, "任务app支付 ", Toast.LENGTH_SHORT).show();
            action = ACTION_APP_TASK_PAY;
            sendPostDelayed(action, s);
        }

        @android.webkit.JavascriptInterface
        /*
         *描述：app大广告主充值
         *请求Url:share/bigrecharge/payment
         */
        public void handleBig(String s) {
//            Toast.makeText(MainActivity.this, "app大广告主充值", Toast.LENGTH_SHORT).show();
            action = ACTION_APP_BIG_AD_RECHARGE;
            sendPostDelayed(action, s);
        }

        /*
         *描述：app小广告主任务加量
         *请求Url:share/extendtask/payment
         */
        @android.webkit.JavascriptInterface
        public void handleSmall(String s) {
//            Toast.makeText(MainActivity.this, "app小广告主任务加量 ", Toast.LENGTH_SHORT).show();
            action = ACTION_APP_SMALL_AD_TASK_ADD;
            sendPostDelayed(action, s);
        }

        /*
         *描述：app购买会员
         *请求Url:share/extendtask/payment
         */
        @android.webkit.JavascriptInterface
        public void handle(String s) {
//            Toast.makeText(MainActivity.this, "购买Vip", Toast.LENGTH_SHORT).show();
            action = ACTION_APP_BUY_VIP;
            sendPostDelayed(action, s);
        }

        /*
         *描述：app发布任务
         *请求Url:task/app/issue/task
         */
        @android.webkit.JavascriptInterface
        public void publicTask(String s) {
//            Toast.makeText(MainActivity.this, "app发布任务", Toast.LENGTH_SHORT).show();
            action = ACTION_APP_ISSUE_TASK;
            sendPostDelayed(action, s);
        }
    }

    private <T> T getResponse(String json, TypeToken<T> typeToken) {
        Gson gson = new Gson().newBuilder().create();
        if (json != null && !json.isEmpty() && typeToken != null) {
            return gson.fromJson(json, typeToken.getType());
        }
        return null;
    }

    private void sendPostDelayed(int action, String json) {

        String REQUEST = "request";
        switch (action) {
            case ACTION_APP_TASK_PAY:
                TypeToken<RequestTaskPay> typeToken1 = new TypeToken<RequestTaskPay>() {
                };
                requestTaskPay = getResponse(json, typeToken1);
                if (requestTaskPay != null) {
                    requestTaskPay.id = (int) SPUtils.get(MainActivity.this, ConstantsConfig.USER_ID, -1);
                }
                paramsMap.put(REQUEST, requestTaskPay);
                break;
            case ACTION_APP_BIG_AD_RECHARGE:
                TypeToken<RequestBigRecharge> typeToken2 = new TypeToken<RequestBigRecharge>() {
                };
                requestBigRecharge = getResponse(json, typeToken2);
                if (requestBigRecharge != null) {
                    requestBigRecharge.id = (int) SPUtils.get(MainActivity.this, ConstantsConfig.USER_ID, -1);
                }
                paramsMap.put(REQUEST, requestBigRecharge);
                break;
            case ACTION_APP_SMALL_AD_TASK_ADD:
                TypeToken<RequestSmallAdTaskAdd> typeToken3 = new TypeToken<RequestSmallAdTaskAdd>() {
                };
                requestSmallAdTaskAdd = getResponse(json, typeToken3);
                if (requestSmallAdTaskAdd != null) {
                    requestSmallAdTaskAdd.id = (int) SPUtils.get(MainActivity.this, ConstantsConfig.USER_ID, -1);
                }
                paramsMap.put(REQUEST, requestSmallAdTaskAdd);
            case ACTION_APP_BUY_VIP:
                TypeToken<RequestBuyVip> typeToken4 = new TypeToken<RequestBuyVip>() {
                };
                requestBuyVip = getResponse(json, typeToken4);
                if (requestBuyVip != null) {
                    requestBuyVip.id = (int) SPUtils.get(MainActivity.this, ConstantsConfig.USER_ID, -1);
                }
                paramsMap.put(REQUEST, requestBuyVip);
                break;
            case ACTION_APP_ISSUE_TASK:
                TypeToken<RequestPublicTask> typeToken5 = new TypeToken<RequestPublicTask>() {
                };
                requestPublicTask = getResponse(json, typeToken5);
                if (requestPublicTask != null) {
                    requestPublicTask.id = (int) SPUtils.get(MainActivity.this, ConstantsConfig.USER_ID, -1);
                }
                paramsMap.put(REQUEST, requestPublicTask);
                break;
        }
        mHandler.postDelayed(mRunnable, 1000);
    }

    class ThirdPlatformWx {
        @android.webkit.JavascriptInterface
        public void handle() {
            openWx();
        }

        @android.webkit.JavascriptInterface
        public void handleQQ(String s) {
            openQQ(s);
        }

        @android.webkit.JavascriptInterface
        public void handleAuth() {
            showFriendlyHintDialog();
            runOnUiThread(() -> iv_background.setVisibility(View.VISIBLE));
        }

        @android.webkit.JavascriptInterface
        public void handleToken() {
            showAuthorizeLoginDialog();
            runOnUiThread(() -> iv_background.setVisibility(View.VISIBLE));
        }
    }

    private void openWx() {
        Intent lan = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(lan.getComponent());
        startActivity(intent);
    }

    private void openQQ(String s) {
        RequestQQ requestQQ = getRequestQQ(s);
        if (requestQQ == null) {
            return;
        }
        String url = requestQQ.url;
        try {
            //uin是发送过去的qq号码
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        } catch (Exception e) {
            Toast.makeText(this, "您还没有安装QQ，请先安装软件", Toast.LENGTH_SHORT).show();
        }
    }


    private RequestQQ getRequestQQ(String s) {
        return new Gson().fromJson(s, new TypeToken<RequestQQ>() {
        }.getType());
    }

    private void showAuthorizeLoginDialog() {
        TokenEmptyDialog tokenEmptyDialog = new TokenEmptyDialog();
        tokenEmptyDialog.setWxAuthorizeListener(this);
        tokenEmptyDialog.show(getSupportFragmentManager(), "TokenEmptyDialog");
    }

    @Override
    public void wxAuthorize() {
        initBroadCast();
        WXLogin();
    }

    private void initBroadCast() {
        //注册广播接收器
        wxAuthorizeBroadCast = new WXAuthorizeBroadCast();
        wxAuthorizeBroadCast.setWxAuthorizeInfoListener(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WXAuthorizeBroadCast.WX_AUTHORIZE_ACTION);
        registerReceiver(wxAuthorizeBroadCast, intentFilter);
    }

    private void WXLogin() {
        try {
            IWXAPI api = WXAPIFactory.createWXAPI(this, ConstantsConfig.WX_APP_ID, false);
            // 判断是否安装了微信客户端
            if (!isWeiXinInstall(MainActivity.this, api)) {
                Toast.makeText(this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
                return;
            }
            // 发送授权登录信息，来获取code
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "qianhe";
            api.sendReq(req);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //判断是否安装了微信
    public boolean isWeiXinInstall(Context context, IWXAPI mWXApi) {
        if (mWXApi.isWXAppInstalled()) {
            return true;
        } else {
            final PackageManager packageManager = context.getPackageManager();
            if (packageManager == null) {
//                Toast.makeText(MainActivity.this, "获取管理器失败", Toast.LENGTH_LONG).show();
                return false;
            }
            // 获取packagemanager
            @SuppressLint("QueryPermissionsNeeded")
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
            if (pinfo != null) {
//                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < pinfo.size(); i++) {
                    String pn = pinfo.get(i).packageName;
//                    if (pn.contains("com.tencent.mm")) {
//                        Toast.makeText(MainActivity.this, pn
//                                        + "\n"
//                                        + "包含微信包名"
//                                , Toast.LENGTH_LONG).show();
//                    }
//                    builder.append(pn).append("\n");
                    if (pn.equalsIgnoreCase("com.tencent.mm")) {
                        return true;
                    }
                }
//                Toast.makeText(MainActivity.this, builder.toString(), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "获取应用列表为空", Toast.LENGTH_LONG).show();
                return false;
            }
        }
        return false;
    }

    @Override
    public void getAuthorizeInfoSuccess(String state, String code) {
        unregisterReceiver(wxAuthorizeBroadCast);
        sendGetTokenRequest(state, code);
    }

    private void sendGetTokenRequest(String state, String code) {
        runOnUiThread(this::showLoading);
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL_1)
                .appendUrl("wechat/user?code=" + code + "&state=" + state + "&type=" + "android")
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new StringObserver() {
                    @Override
                    protected void onSuccess(String json) {
                        try {
                            String token = getToken(json);
                            saveToken(token);
                            sendGetWxUserInfo(token);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        runOnUiThread(() -> showLoading());
                        String message = "";
                        if (code != null) {
                            message = message + code + "\n";
                        }
                        message = message + msg;
                        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        super.onError(e);
                        runOnUiThread(() -> hideLoading());
                    }
                });
    }

    private String getToken(String json) {
        String token;
        Gson gson = new Gson().newBuilder().create();
        BaseResponse<AuthorizeInfo> response = gson.fromJson(json, new TypeToken<BaseResponse<AuthorizeInfo>>() {
        }.getType());
        AuthorizeInfo authorizeInfo = gson.fromJson(gson.toJson(response.data), new TypeToken<AuthorizeInfo>() {
        }.getType());
        token = authorizeInfo.token;
        SPUtils.put(MainActivity.this, ConstantsConfig.USER_NAME, authorizeInfo.username);
        SPUtils.put(MainActivity.this, ConstantsConfig.USER_PHOTO, authorizeInfo.avatar);
        SPUtils.put(MainActivity.this, ConstantsConfig.USER_ID, authorizeInfo.id);
        return token;
    }

    private void saveToken(String token) {
        SPUtils.put(MainActivity.this, ConstantsConfig.TOKEN, token);
    }

    private void sendGetWxUserInfo(String token) {
        if (token == null || token.isEmpty()) {
            Toast.makeText(MainActivity.this, "用户登录缺少必要的参数", Toast.LENGTH_SHORT).show();
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL_1)
                .appendUrl("user/info?token=" + token)
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new StringObserver() {
                    @Override
                    protected void onSuccess(String json) {
                        runOnUiThread(() -> hideLoading());
                        WXUserInfo info = getWxUserInfo(json);
                        int is_sex_unknown = getIsSex(info);
                        saveWXUserInfo(is_sex_unknown);
                        if (is_sex_unknown == 2) {
                            showFriendlyHintDialog();
                        } else {
                            iv_background.setVisibility(View.GONE);
                            String url = NetUrlConfig.BASE_URL + "/#/authorize1/" + token + "&app=app";
                            webView.loadUrl(url);
                            int currentCode = PackageUtils.getVersionCode(MainActivity.this);
                            checkVersion(currentCode, false);
                        }
                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        runOnUiThread(() -> hideLoading());
                        String message = "";
                        if (code != null) {
                            message = message + code + "\n";
                        }
                        message = message + msg;
                        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        super.onError(e);
                        runOnUiThread(() -> hideLoading());
                    }
                });
    }

    private WXUserInfo getWxUserInfo(String json) {
        Gson gson = new Gson().newBuilder().create();
        BaseResponse<WXUserInfo> response = gson.fromJson(json, new TypeToken<BaseResponse<WXUserInfo>>() {
        }.getType());
        return gson.fromJson(gson.toJson(response.data), new TypeToken<WXUserInfo>() {
        }.getType());
    }

    private int getIsSex(WXUserInfo info) {
        int isSex = 2;
        if (info != null) {
            isSex = info.is_sex_unknown;
        }
        SPUtils.put(MainActivity.this, ConstantsConfig.IS_SEX, String.valueOf(isSex));
        return isSex;
    }

    private void saveWXUserInfo(int is_sex_unknown) {
        SPUtils.put(this, ConstantsConfig.IDENTIFICATION, is_sex_unknown);
    }

    private void showFriendlyHintDialog() {
        IdentificationUnknownDialog identificationUnknownDialog = new IdentificationUnknownDialog();
        identificationUnknownDialog.setOpenWxListener(this);
        identificationUnknownDialog.show(getSupportFragmentManager(), "IdentificationUnknownDialog");
    }

    @Override
    public void openWxToPersonalInfo() {
        Log.i("TAG", "");
        iv_background.setVisibility(View.GONE);
        String token = (String) SPUtils.get(this, ConstantsConfig.TOKEN, "1");
        String url = NetUrlConfig.BASE_URL + "/#/authorize1/" + token + "&app=app";
        webView.loadUrl(url);
        int currentCode = PackageUtils.getVersionCode(MainActivity.this);
        checkVersion(currentCode, false);
    }

    @Override
    public void getAuthorizeInfoFail(String errInfo) {
        unregisterReceiver(wxAuthorizeBroadCast);
    }

    private final String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.READ_EXTERNAL_STORAGE};

    class SaveImage {
        @android.webkit.JavascriptInterface
        public void handle(String s) {
            Log.i("TAG", s);
            String url = getImageUrl(s);
            int type = getImageType(s);
            paramsMap.put("URL", url);
            paramsMap.put("TYPE", type);
            checkPermissions(permissions);
        }
    }

    private int getImageType(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        SaveImageResponse response = new Gson().fromJson(s, new TypeToken<SaveImageResponse>() {
        }.getType());
        if (response == null) {
            return 0;
        }
        return response.type;
    }

    private String getImageUrl(String s) {
        if (s == null || s.isEmpty()) {
            return null;
        }
        SaveImageResponse response = new Gson().fromJson(s, new TypeToken<SaveImageResponse>() {
        }.getType());
        if (response == null || response.url == null || response.url.isEmpty()) {
            return null;
        }
        return response.url;
    }

    private void checkPermissions(String... permissions) {
        int targetSdkVersion = 0;
        try {
            final PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;//获取应用的Target版本
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
//            Log.e("err", "检查权限_err0");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //Build.VERSION.SDK_INT是获取当前手机版本 Build.VERSION_CODES.M为6.0系统
            //如果系统>=6.0
            if (targetSdkVersion >= Build.VERSION_CODES.M) {
                //第 1 步: 检查是否有相应的权限
                boolean isAllGranted = checkPermissionAllGranted(permissions);
                if (isAllGranted) {
                    //Log.e("err","所有权限已经授权！");
                    loadImageUrl();
                    return;
                }
                // 一次请求多个权限, 如果其他有权限是已经授予的将会自动忽略掉
                ActivityCompat.requestPermissions(this,
                        permissions, 1001);
            }
        } else {
            loadImageUrl();
        }
    }

    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                //Log.e("err","权限"+permission+"没有授权");
                return false;
            }
        }
        return true;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1001) {
            boolean isAllGranted = true;
            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }
            if (isAllGranted) {
                // 所有的权限都授予了
                Log.e("err", "权限都授权了");
                loadImageUrl();
            } else {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
                //容易判断错
                //MyDialog("提示", "某些权限未开启,请手动开启", 1) ;
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);//注意就是"package",不用改成自己的包名
                intent.setData(uri);
                startActivityForResult(intent, 1002);
            }
        }
    }


    private void loadImageUrl() {
        int type = (int) paramsMap.get("TYPE");
        if (type == 0) {
            String url = (String) paramsMap.get("URL");
            if (url == null || url.isEmpty()) {
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "图片地址为空", Toast.LENGTH_SHORT).show());
                return;
            }
            new Thread(() -> Glide
                    .with(MainActivity.this)
                    .asBitmap()
                    .load(url)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            String fileName = getFileName();
                            saveBitmap(MainActivity.this, resource, fileName);
                        }
                    })).start();
        } else {
            if (type == 1) {
                showPlaybillDialog();
            }
            if (type == 2) {
                showResultDialog();
            }
        }
    }

    private void showResultDialog() {
        ResultDialog dialog = new ResultDialog();
        dialog.show(getSupportFragmentManager(), "ResultDialog");
    }

    private void showPlaybillDialog() {
        PlaybillDialog dialog = new PlaybillDialog();
        dialog.show(getSupportFragmentManager(), "PlaybillDialog");
    }

    private String getFileName() {
        Calendar cal = Calendar.getInstance();

        //当前年
        int year = cal.get(Calendar.YEAR);
        //当前月
        int month = (cal.get(Calendar.MONTH)) + 1;
        //当前月的第几天：即当前日
        int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
        //当前时：HOUR_OF_DAY-24小时制；HOUR-12小时制
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        //当前分
        int minute = cal.get(Calendar.MINUTE);
        //当前秒
        int second = cal.get(Calendar.SECOND);
        String time = year + ""
                + month + ""
                + day_of_month + ""
                + hour + ""
                + minute + ""
                + second;

        return time + ".jpg";
    }

    /*
     * 保存文件，文件名为当前日期
     */

    public void saveBitmap(Context context, Bitmap bitmap, String bitName) {
        if (bitmap == null) {
            runOnUiThread(() -> Toast.makeText(MainActivity.this, "图片资源为空", Toast.LENGTH_SHORT).show());
            return;
        }
        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else { // Meizu 、Oppo
            Log.v("qwe", "002");
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
        file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 发送广播，通知刷新图库的显示
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
        runOnUiThread(() -> Toast.makeText(MainActivity.this, "保存图片成功", Toast.LENGTH_SHORT).show());
    }

    class AppUpdate {
        @android.webkit.JavascriptInterface
        public void handle() {

            Log.i("TAG", "");
            int currentCode = PackageUtils.getVersionCode(MainActivity.this);
            new Thread(() -> checkVersion(currentCode, true)).start();
        }
    }

    private void checkVersion(int currentCode, boolean toast) {
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL_1)
                .appendUrl("help/versions")
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new StringObserver() {
                    @Override
                    protected void onSuccess(String json) {
                        UpdateResponse response = getUpdateResponse(json);
                        checkUpData(response, currentCode, toast);
                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        String message = "";
                        if (code != null) {
                            message = message + code + "\n";
                        }
                        message = message + msg;
                        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        super.onError(e);
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private UpdateResponse getUpdateResponse(String json) {
        if (json != null && !json.isEmpty()) {
            Gson gson = new Gson().newBuilder().create();
            BaseResponse<UpdateResponse> baseResponse = gson.fromJson(json, new TypeToken<BaseResponse<UpdateResponse>>() {
            }.getType());
            if (baseResponse != null && baseResponse.data != null) {
                return gson.fromJson(gson.toJson(baseResponse.data), new TypeToken<UpdateResponse>() {
                }.getType());
            }

        }

        return null;
    }

    private void checkUpData(UpdateResponse response, int currentCode, boolean toast) {
        if (response != null) {
            int versions_set = response.versions_set;
            if (currentCode < versions_set) {
                String url = response.url;
                paramsMap.put(DOWNLOAD_URL, url);
                showUpgradeDialog();
            } else {
                if (toast) {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "已是最新版本\n无需更新", Toast.LENGTH_SHORT).show());
                }
            }
        }
    }

    private void showUpgradeDialog() {
        AppUpdateDialog appUpdateDialog = new AppUpdateDialog();
        appUpdateDialog.setAppUpgradeListener(() -> {
            censusDownloadCount();
        });
        appUpdateDialog.show(getSupportFragmentManager(), "AppUpdateDialog");
    }

    /**
     * 统计下载数量
     */
    private void censusDownloadCount() {
        new Thread(() -> {
            runOnUiThread(this::showLoading);
            new RetrofitHelper
                    .Builder()
                    .baseUrl(NetUrlConfig.BASE_URL_1)
                    .appendUrl(" help/appdownload")
                    .build()
                    .observable(RequestEnum.METHOD_DOWNLOAD)
                    .subscribe(new StringObserver() {
                        @Override
                        protected void onSuccess(String json) {
                            runOnUiThread(() -> {
                                hideLoading();
                            });
                            mHandler.postDelayed(mUpdateRunnable, 1500);

                        }

                        @Override
                        protected void onFailed(Integer code, String msg) {
                            runOnUiThread(() -> hideLoading());
                            String url = (String) paramsMap.get(DOWNLOAD_URL);
                            openBrowser(MainActivity.this, url);
                        }
                    });
        }).start();
    }

    /**
     * 调用第三方浏览器打开
     *
     * @param context
     * @param url     要浏览的资源地址
     */
    @SuppressLint("QueryPermissionsNeeded")
    public void openBrowser(Context context, String url) {
        if (url == null || url.isEmpty()) {
            runOnUiThread(() -> Toast.makeText(MainActivity.this, "路径不存在", Toast.LENGTH_SHORT).show());
            return;
        }
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            // 打印Log   ComponentName到底是什么
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            Toast.makeText(context.getApplicationContext(), "请下载浏览器", Toast.LENGTH_SHORT).show();
        }
    }


    private void downloadFile(String url) {
        runOnUiThread(this::showLoading);
        new RetrofitHelper
                .Builder()
                .baseUrl(url)
                .appendUrl("weishi_guanwang.apk")
                .build()
                .observable(RequestEnum.METHOD_DOWNLOAD)
                .subscribe(new DownloadObserver() {
                    @Override
                    protected void onSuccess(ResponseBody body) {
                        new Thread(() -> {
                            try {
                                String dirPath = getSDPath();
                                File file = getTargetFile(dirPath, "千禾.apk");
                                InputStream inputStream = body.byteStream();
                                writeFileFromIS(file, inputStream);
                                runOnUiThread(() -> hideLoading());
                            } catch (Exception e) {
                                e.printStackTrace();
                                runOnUiThread(() -> Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show());
                            }

                        }).start();

                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show());
                    }
                });
    }

    private String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = getExternalFilesDir("");
        }
        return sdDir != null ? sdDir.toString() : null;
    }

    private File getTargetFile(String parentPath, String name) {

        try {
            File parentFile = new File(parentPath);
            if (parentFile == null || !parentFile.exists()) {
                parentFile.mkdirs();
            }
            String path = parentFile.getAbsolutePath() + "/" + name;
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //将输入流写入文件
    private static void writeFileFromIS(File file, InputStream is) {
        try {
            int len;
            long currentLength = 0;
            OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
            byte[] data = new byte[1024 * 8];
            while ((len = is.read(data, 0, 1024 * 8)) != -1) {
                os.write(data, 0, len);
                currentLength += len;
                //计算当前下载进度
                int progress = (int) (100 * currentLength / data.length);
            }
            //下载完成，并返回保存的文件路径
            is.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //创建文件

    }

    class BannerPlay {
        @android.webkit.JavascriptInterface
        public void handle(String s) {
            String url = getIBannerUrl(s);
            if (url == null || url.isEmpty()) {
                Toast.makeText(MainActivity.this, "路径不存在", Toast.LENGTH_SHORT).show();
                return;
            }
            openBrowser(MainActivity.this, url);
//            Bundle mBundle = new Bundle();
//            mBundle.putSerializable(ConstantsConfig.VALUE, url);
//            Intent mIntent = new Intent(MainActivity.this, BannerHandlerActivity.class);
//            mIntent.putExtras(mBundle);
//            startActivity(mIntent);
        }
    }

    private String getIBannerUrl(String s) {
        if (s == null || s.isEmpty()) {
            return null;
        }
        BannerResponse response = new Gson().fromJson(s, new TypeToken<BannerResponse>() {
        }.getType());
        if (response == null || response.url == null || response.url.isEmpty()) {
            return null;
        }
        return response.url;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                showExitDialog();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showExitDialog() {
        AppExitDialog appExitDialog = new AppExitDialog();
        appExitDialog.setAppExitListener(this::finish);
        appExitDialog.show(getSupportFragmentManager(), "AppExitDialog");
    }
}
